package org.toolbook.controller;

import java.util.Date;

import javax.servlet.http.Cookie;

import org.toolbook.interceptor.LoginInterceptor;
import org.toolbook.model.User;
import org.toolbook.util.FileUtils;
import org.toolbook.util.LogUtil;
import org.toolbook.util.MD5Util;
import org.toolbook.util.PropUtil;
import org.toolbook.validator.LoginValidator;
import org.toolbook.validator.RegValidator;
import org.toolbook.validator.UpdatePwdValidator;
import org.toolbook.validator.UploadHeadValidator;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
/**
 * 用户控制器
 * @author meigang
 * @date 2015-06-20 18:23
 */
public class UserController extends Controller{
	
	/**
	 * 注册用户
	 */
	@Before(RegValidator.class)
	public void regUser(){
		User u = new User().set("username", getPara("username"))
				.set("email", getPara("email"))
				.set("password", MD5Util.md5(getPara("password")))
				.set("head", "head/default.jpg")
				.set("registerTime", new Date())
				.set("status", "1");
		u.save();
		//写日志
		LogUtil.log.info("新用户"+u.get("username")+"注册成功");
		//存入session
		setSessionAttr(PropUtil.getProperty("SESSION_LOGIN_KEY"), u);
		redirect("/general");
	}
	/**
	 * 登陆用户
	 */
	@Before(LoginValidator.class)
	public void login(){
		User u = User.dao.checkLoginUser(getPara("username"), getPara("password"));
		//更新最近登录时间
		u.set("lastLoginTime", new Date()).update();
		//自动登陆被选中
		if(getPara("auto_login") != null){
			Cookie cookie = new Cookie(PropUtil.getProperty("COOKIE_LOGIN_KEY"), u.get("username").toString() + "-" + u.get("password").toString());
			cookie.setMaxAge(Integer.parseInt(PropUtil.getProperty("cookieTime")) * 24 * 60 * 60);
			cookie.setPath("/");
			getResponse().addCookie(cookie);
			LogUtil.log.info("用户"+u.get("username")+"开启自动登陆，写cookie成功");
		}
		//写日志
		LogUtil.log.info("用户"+u.get("username")+"登陆成功");
		//存入session
		setSessionAttr(PropUtil.getProperty("SESSION_LOGIN_KEY"), u);
		redirect("/general");
	}
	/**
	 * 安全退出
	 */
	@Before(LoginInterceptor.class)
	public void logout(){
		User u = getSessionAttr(PropUtil.getProperty("SESSION_LOGIN_KEY"));
		clearSessionAndCookie();
		LogUtil.log.info("用户[ "+u.get("username")+" ]已安全退出系统");
		render("/index.jsp");
	}
	/**
	 * 跳到修改密码的界面
	 */
	@Before(LoginInterceptor.class)
	public void toUpdatePwd(){
		render("/WEB-INF/pages/fc/user/updatePwd.jsp");
	}
	/**
	 * 跳到修改头像的界面
	 */
	@Before(LoginInterceptor.class)
	public void toUpdateHead(){
		render("/WEB-INF/pages/fc/user/updateHead.jsp");
	}
	/**
	 * 修改密码
	 */
	@Before({LoginInterceptor.class,UpdatePwdValidator.class})
	public void updatePwd(){
		User user = getSessionAttr(PropUtil.getProperty("SESSION_LOGIN_KEY"));
		if(User.dao.findById(user.get("id")).set("password", MD5Util.md5(getPara("newPwd"))).update()){
			//密码修改成功，重新登录
			LogUtil.log.info("用户[ "+user.get("username")+" ]修改密码成功");
			clearSessionAndCookie();
			render("/index.jsp");
		}else{
			//密码修改失败
			LogUtil.log.info("用户[ "+user.get("username")+" ]修改密码失败");
			setAttr("nopass", 1);
			setAttr("oldPwd", "未知原因，密码修改未成功");
			render("/WEB-INF/pages/fc/user/updatePwd.jsp");
		}
	}
	/**
	 * 清除session和cookie
	 */
	private void clearSessionAndCookie() {
		//删除session
		getSession().invalidate();
		//删除cookie
		Cookie cookie = new Cookie(PropUtil.getProperty("COOKIE_LOGIN_KEY"),null);
		cookie.setMaxAge(0);
		cookie.setPath("/");
		getResponse().addCookie(cookie);
	}
	@Before({LoginInterceptor.class,UploadHeadValidator.class})
	public void uploadHead(){
		//先删掉/head/id/的所有文件,为了防止多次修改头像后，头像文件冗余
		User u = getSessionAttr(PropUtil.getProperty("SESSION_LOGIN_KEY"));
		String fileName = getFile("head").getFileName();
		FileUtils.deleteAllFileInDirOutFileName(PathKit.getWebRootPath() + "/head/" + u.get("id"),fileName);
		//将文件路径update到该用户记录中
		u.set("head", "head/"+ u.get("id") + "/" + fileName).update();
		setSessionAttr(PropUtil.getProperty("SESSION_LOGIN_KEY"), u);
		setAttr("isSuccess", 1);
		setAttr("success_info", "恭喜，头像修改成功");
		LogUtil.log.info("用户[ "+u.get("username")+" ]修改头像成功");
		render("/WEB-INF/pages/fc/user/updateHead.jsp");
	}
	
}
